package com.game.server;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import com.game.share.Global;

/**
 * 这个线程的目的是删除session
 * 
 * @ TODO 如何关闭这个线程？
 * 
 * @author yedawei
 * 
 */
public class SessionThread implements Runnable {
	class SessionBlock {
		SessionBlock(Session session, long time) {
			this.session = session;
			this.time = time;
		}

		final Session session;
		final long time;
	}

	private final BlockingQueue<SessionBlock> queue;

	public SessionThread() {
		queue = new LinkedBlockingQueue<SessionBlock>();
	}

	@Override
	public void run() {
		while (true) {
			SessionBlock block = queue.peek();
			long deltaTime = Global.SESSION_TIME - (System.currentTimeMillis() - block.time);
			if(deltaTime > 0){
				try {
					Thread.sleep(deltaTime);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				
			}
		}
	}

	public void remove(Session session) {
		SessionBlock block = new SessionBlock(session,
				System.currentTimeMillis());
		try {
			queue.put(block);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
